package com.wuyou.simple;

import java.util.Arrays;

/**
 * 1796. 字符串中第二大的数字
 */
public class SecondHighest {

    public static void main(String[] args) {
        String s = "sjhtz8344";
        System.out.println(solution_2(s));
    }


    // 3ms
    public static int solution_3(String s){
        char[] chars = s.toCharArray();
        char maxNum = 0;
        int secondNum = -1;
        for (int i = 0; i < chars.length; i++) {
            if(Character.isLetter(chars[i])) continue;
            if (chars[i] > maxNum) {
                secondNum = maxNum == 0 ? secondNum : maxNum - '0';
                maxNum = chars[i];
            }else if(chars[i] < maxNum){
                secondNum = Math.max(secondNum, chars[i] - '0');
            }
        }
        return secondNum;
    }

    // 4ms
    public static int solution_2(String s){
        char[] chars = s.toCharArray();
        Arrays.sort(chars);
        char maxNum = 0;
        int secondNum = -1, i = 0;
        while (i <= chars.length) {
            if (chars[i] > '9') break;
            if (chars[i] > maxNum) {
                secondNum = maxNum == 0 ? secondNum : Integer.parseInt(maxNum + "");
                maxNum = chars[i];
            }else if(chars[i] < maxNum){
                secondNum = Math.max(secondNum, Integer.parseInt(chars[i] + ""));
            }
            i++;
        }
        return secondNum;
    }


    // 2ms
    public static int solution_1(String s){
        char[] chars = s.toCharArray();
//        Arrays.sort(chars);
        char maxNum = 0;
        int secondNum = -1;
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] > '9') continue;
            if (chars[i] > maxNum) {
                secondNum = maxNum == 0 ? secondNum : Integer.parseInt(maxNum + "");
                maxNum = chars[i];
            }else if(chars[i] < maxNum){
                secondNum = Math.max(secondNum, Integer.parseInt(chars[i] + ""));
            }
        }
        return secondNum;
    }
}
